package api

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"seat-service/initialization"
	"seat-service/model"
	"seat-service/response"
	service "seat-service/service/impl"
	"time"
)

var availableService service.AvailableService

type AvailableApi struct {
}

func (*AvailableApi) All(c *gin.Context) {
	data, err := availableService.GetAll()
	if err != nil {
		initialization.SeatLogger.Error("availableService.GetAll() failed", zap.Error(err))
		resp.Fail(c, response.CodeServerBusy, nil)
		return
	}
	resp.Success(c, response.CodeSuccess, data)
}

func (*AvailableApi) Save(c *gin.Context) {
	par := model.AvailableTime{}
	if err := c.ShouldBind(&par); err != nil {
		initialization.SeatLogger.Error("c.ShouldBind(&par) failed", zap.Error(err))
		resp.Fail(c, response.CodeParamError, nil)
		return
	}
	// 定义时间格式
	timeLayout := "15:04"
	start, err := time.Parse(timeLayout, par.Start)
	if err != nil {
		initialization.SeatLogger.Error("time.Parse(par.Start,timeLayout) failed", zap.Error(err))
		resp.Fail(c, response.CodeParamError, nil)
		return
	}
	end, err := time.Parse(timeLayout, par.End)
	if err != nil {
		initialization.SeatLogger.Error("time.Parse(par.End,timeLayout) failed", zap.Error(err))
		resp.Fail(c, response.CodeParamError, nil)
		return
	}
	if start.After(end) {
		initialization.SeatLogger.Error("time.Parse(par.End,timeLayout) failed", zap.Error(err))
		resp.Fail(c, response.CodeParamError, nil)
		return
	}

	err = availableService.Save(&par)
	if err != nil {
		initialization.SeatLogger.Error("availableService.Save(par) failed", zap.Error(err))
		resp.Fail(c, response.CodeServerBusy, nil)
		return
	}
	resp.Success(c, response.CodeSuccess, nil)
}
